package com.esun.payment_api.controller;

import com.esun.common.api.CommonResult;
import com.esun.common.utils.BlankUtils;
import com.esun.common.utils.ExcelUtils;
import com.esun.payment_api.bean.InvContentDetailBean;
import com.esun.payment_api.bean.InvContentImportBean;
import com.esun.payment_api.domain.InvFormContent;
import com.esun.payment_api.domain.TExcelTableCol;
import com.esun.payment_api.dto.InvContentParam;
import com.esun.payment_api.service.CommonService;
import com.esun.payment_api.service.InvFormContentService;
import com.esun.payment_api.service.TExcelTableColService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 发票-开票内容接口
 * Create by benett on 2022-03-10
 */
@RestController
@RequestMapping("/inv/content")
public class InvFormContentController {

    @Resource
    InvFormContentService invFormContentService;

    @Resource
    TExcelTableColService tExcelTableColService;

    @Resource
    CommonService commonService;

    //此接口已弃用，发票-开票内容：新增
    @PostMapping("/insert")
    @ResponseBody
    public CommonResult insert(@RequestBody InvFormContent record) {
        int count = invFormContentService.insert(record);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("发票-开票内容：根据Id删除")
    @RequestMapping ("/deleteById")
    public CommonResult deleteById(BigDecimal id) {
        try {
            System.out.println("删除开票内容接口，ID="+id);
            int count = invFormContentService.deleteById(id);
            if (count > 0) {
                return CommonResult.success(count);
            } else {
                return CommonResult.failed("删除失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("删除失败！");
        }
    }

    //此接口已弃用，发票-开票内容：删除,支持批量
    @PostMapping("/delete")
    @ResponseBody
    public CommonResult delete(@RequestParam("ids") List<BigDecimal> ids) {
        int count = invFormContentService.delete(ids);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("发票-开票内容：修改/保存")
    @PostMapping("/update")
    @ResponseBody
    public CommonResult update(@RequestBody InvFormContent record) {
        if (record == null) {
            return CommonResult.failed("请检查参数");
        }
        if (BlankUtils.isBlank(record.getId())) {
            return CommonResult.failed("id不能为空");
        }
        int count = invFormContentService.update(record);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("发票-开票内容：根据id查看单个开票内容")
    @GetMapping("/getById")
    public CommonResult<InvContentDetailBean> getById(@RequestParam BigDecimal id) {
        if (BlankUtils.isBlank(id)){
            CommonResult.failed("id不能为空");
        }
        InvContentDetailBean invContentDetail = invFormContentService.getById(id);
        return CommonResult.success(invContentDetail);
    }

    //此接口已弃用，发票-开票内容：根据发票id返回开票内容列表
//    @GetMapping("/getListByInvId")
//    @ResponseBody
//    public CommonResult<List<InvFormContent>> getListByInvId(@RequestParam Short invId) {
//        List<InvFormContent> invFormContentList = invFormContentService.getListByInvId(invId);
//        return CommonResult.success(invFormContentList);
//    }

    @ApiOperation("发票-开票内容：新增多条")
    @RequestMapping("/insertMultiple")
    public CommonResult insertMultiple(@RequestBody InvContentParam param) {
        Integer invId = param.getInvId();
        Short coId = param.getCoId();
        Short createBy = param.getCreateBy();
        BigDecimal taxRate = param.getTaxRate();
        List<InvFormContent> records = param.getList();
        for (InvFormContent record : records) {
            record.setCoId(coId);
            record.setInvId(invId);
            record.setCreateBy(createBy);
            record.setTaxRate(taxRate);
            if (BlankUtils.isBlank(record.getMoney())) {
                return CommonResult.failed("请填写开票金额！");
            }
        }
        //System.out.println("List赋值完毕");
        try {
            int count = invFormContentService.insertMultiple(records);
            if (count > 0) {
                return CommonResult.success(count);
            } else {
                return CommonResult.failed("新增开票内容失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("添加失败");
        }
    }

    @ApiOperation("发票-开票内容：批量导入")
    @RequestMapping("/excelImport")
    public CommonResult excelImport(@RequestParam MultipartFile file, InvContentImportBean importParam) throws IOException {
        //导入中间表
        String midTableName = "sys_import_data";
        //导入最终表名
        String tableName = "inv_form_content";
        System.out.println("开票内容导入：" + file.getOriginalFilename() + "---->" + tableName);

        List<TExcelTableCol> excelParams = tExcelTableColService.getParamByTableName(tableName);
        //调用Util工具类，获取map
        String collectionName = "xcx_kpnr";
        Map<Integer, String> sqlMap = ExcelUtils.excelImport(file, midTableName, collectionName, excelParams);
        try {
            //遍历map的value，即sql语句，导入中间表sys_import_data
            for (String sql : sqlMap.values()) {
                //入库
                System.out.println(sql);
                commonService.insertOne(sql);
            }
        } catch (Exception e){
            return CommonResult.failed("数据中转导入失败");
        }
        System.out.println(midTableName + "表数据导入成功！");
        try {
            //导入最终表inv_form_content
            tExcelTableColService.importContentFromMidTable(importParam);
        } catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("开票内容导入失败");
        }
        System.out.println(tableName + "表数据导入成功！");
        return CommonResult.success("开票内容导入成功");
    }

    @GetMapping("/sumMoneyByInvId")
    @ResponseBody
    public CommonResult sumMoneyByInvId(Integer invId) {
        try {
            return CommonResult.success(invFormContentService.sumMoneyByInvId(invId));
        } catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("查询开票内容总金额失败");
        }
    }

}
